﻿using System;
using System.Runtime.InteropServices;
using Acrobat;

namespace PdfRotator
{
    internal class PdfDoc : IDisposable
    {
        private readonly AcroPDDoc _pdDoc;

        public PdfDoc(string path)
        {
            _pdDoc = new AcroPDDoc();
            if (!_pdDoc.Open(path))
            {
                throw new ArgumentException("Failed to open " + path);
            }
        }

        public void ForEach(Action<AcroPDPage> action)
        {
            ForEach((pdPage, i) => action(pdPage));
        }

        public void ForEach(Action<AcroPDPage, int> action)
        {
            int num = _pdDoc.GetNumPages();
            for (int i = 0; i < num; i++)
            {
                var page = (AcroPDPage) _pdDoc.AcquirePage(i);
                try
                {
                    action(page, i);
                }
                finally
                {
                    Marshal.ReleaseComObject(page);
                }
            }
        }

        public bool Save(string path)
        {
            return _pdDoc.Save(0, path);
        }

        #region IDisposable

        private bool _disposed;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~PdfDoc()
        {
            Dispose(false);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // Dispose managed resources.
                }

                // Dispose unmanaged resources.
                if (_pdDoc != null)
                {
                    _pdDoc.Close();
                }
            }
            _disposed = true;
        }

        #endregion
    }
}